package remote

import (
	"errors"
	"github.com/go-resty/resty/v2"
	"wf-deploy-agent/infra"
	"wf-deploy-agent/registry"
	registry2 "wf-deploy-agent/registry/entity"
)

type Proxy struct {
	client      *resty.Client
	serviceName string
}

func (p *Proxy) make(routingKey ...string) *registry2.ServiceInstance {
	instance := registry.GetInstance(p.serviceName, routingKey...)
	if instance == nil {
		infra.Logger.Errorf("there is no avaiable instance for 【%s】", p.serviceName)
	}

	return instance
}

func (p *Proxy) concatUrl(suffix string, routingKey ...string) string {
	instance := p.make(routingKey...)
	if instance == nil {
		return ""
	}

	return instance.GetHttpPrefix() + suffix
}

func (p *Proxy) get(url string, result any) (*resty.Response, error) {
	if url == "" {
		return nil, errors.New("请求地址不能为空")
	}

	req := p.client.R()

	if result != nil {
		req.SetResult(result)
	}

	return req.Get(url)
}

func (p *Proxy) post(url string, body any, result any) (*resty.Response, error) {
	if url == "" {
		return nil, errors.New("请求地址不能为空")
	}

	req := p.client.R()

	if body != nil {
		req.SetBody(body)
	}

	if result != nil {
		req.SetResult(result)
	}

	return req.Post(url)
}
